package com.jt.auth.service.impl;

import com.jt.auth.service.RemoteUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 我们的项目在完成用户身份认证时,
 * 底层会通过UserDetailsService接口实现类,
 * 获取用户信息(默认是内存,可以是数据库,也可以是远端服务)
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    /**
     * 远程服务(sso-system)调用接口
     */
    @Autowired
    private RemoteUserService remoteUserService;
    /**
     * 基于用户名获取用户以及用户权限信息并封装
     * @param username 这个用户名来自客户端的输入
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.基于用户名获取远端(现在是我们写的system服务)用户信息
        com.jt.auth.pojo.User user =
                remoteUserService.selectUserByUsername(username);
        if(user==null)
            throw new UsernameNotFoundException("user not found");
        //2.基于远端用户id获取用户权限信息
        List<String> permissions =
                remoteUserService.selectUserPermissions(user.getId());
        log.debug("user.permissions:{}",permissions);
        //3.封装用户信息并返回,交给认证管理器(AuthenticationManager)对用户身份进行认证.
        return new User(username,
                user.getPassword(),
                  AuthorityUtils.createAuthorityList(
                        permissions.toArray(new String[]{})));
    }//这个方法我们只负责写,我们自己不调用.
}
